/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: Shentong
 * @Date: 2021-04-09 12:34:34
 * @LastEditors: Shentong
 * @LastEditTime: 2021-11-26 20:50:51
 */
// eslint-disable-next-line @typescript-eslint/no-use-before-define
 import React, { useEffect, useState, useCallback, useMemo, useReducer, useRef } from "react";
 import Taro, { useReachBottom, useDidShow, useShareAppMessage, usePullDownRefresh } from "@tarojs/taro";
 import { View, Swiper, SwiperItem, Image, Text } from "@tarojs/components";

 import ProdItem from '@/src/components/custom/prodItem';

 import { getStoregeByKey } from '@/utils/index'

 import NavBar  from '@/src/components/custom/navBar'
 import NoMore from "@/components/custom/no-more";

 import LocationIcon from '@/src/assets/icon/locationIcon.png'

 import NoDataIcon from '@/src/assets/icon/noDataIcon.png'

 import {getSwiper, getShopList} from '@/api/home'

 import Skeleton from 'taro-skeleton'

 import Nav from "./components/nav";

 import styles from './index.module.scss'

import Category from "./components/categoryList";

interface SwiperItem {
  imageUrl: string;
}

interface TabItem {
  name: string;
  id: string
}

  const listReducer = (state, action) => {
    switch (action.type) {
      case 'init': return action.payload
      case 'concat': return state.concat(action.payload)
      default: return state
    }
  }

 const Home = () => {
   const [tabIndex, setTabIndex] = useState<Number>(0);
   const [swiperList, setSwiperList] = useState<Array<SwiperItem>>([]);
   const [categoryList, setCategoryList] = useState<Array<any>>([]);
   const [categoryLoading, setCategoryloading] = useState<boolean>(true)
   const [shopList, shopListDispatch] = useReducer(listReducer, [])
   const [showSkeleton, setShowSkeleton] = useState<boolean>(true)
   // 销量排序，距离
   const [sortType, setSortType] = useState<string>('0')
   // 分类id
   const [cateId, setCateId] = useState<string | number>(0)
   // 校区Id
   const [schoolId, setSchoolId] = useState<string>('')
   const [school, setSchool] = useState<string>('「选择校区」')
   // 偏移量
   const [offset, setOffset] = useState<Number>(0)
   // 是否加载完所有数据
   const [isLoadFinish, setIsloadFinish] = useState(false)
   /** 非 精选下的内容 start*/
   const [aTabInfo, setTabInfo] = useState<any>({ id: "", title: "" });

   // 一些全局的变量 ：显示骨架屏
   const showSkeletonRef =  useRef(true);

   const requestParams = useRef({});
   requestParams.current = {pageSize: 10, lon: 0, lat: 0};


   const tabsBar = useMemo(()=>{
     return [{name: '销量排序', id: '0'}, {name: '距离', id: '1'}]
   }, [])


   Taro.setBackgroundColor({
    backgroundColor: '#ffa15a', // 窗口的背景色为白色
  })
  Taro.setNavigationBarColor({
    backgroundColor: '#fffff',
    frontColor: '#ffffff'
  })

   // 轮播图
   const getSwiperList = async () => {
    try {
      const {code, data = {}} = await getSwiper()
      if (code === '00000-00000') {
        const { images, cates} = data
        setSwiperList([...images])
        setCategoryList([...cates])
        setCategoryloading(false)
        const [first = {}] = cates
        // 初始化第一个种类id
        setCateId(first.cateId)
      }
    } catch (error) {}
   }

  // 页面初始化
  const pageInit = () => {
    judgeSchool().then(userInfo => {
      const { lon, lat, schoolSId, schoolName } = userInfo

      if (schoolSId) {
        requestParams.current.lon = lon
        requestParams.current.lat = lat
        setSchool(schoolName)
        setSchoolId(userInfo.schoolSId)


      } else {
        schoolSelectModal()
      }
    })
  }


  // 判断用户是否选择了校区
  const judgeSchool = useCallback(async () => {
    // 获取用户信息
    const userInfo = await getStoregeByKey('userInfo')

    return userInfo

  }, [])

  const schoolSelectModal = () => {
    Taro.showModal({
        content: '您没未绑定校区，是否去绑定？',
        confirmText: '确认',
        cancelText: '取消',
        success: async function (res) {
          if (res.confirm) {
            Taro.navigateTo({
              url: '/pages/schoolList/index'
            })
          } else {
            // console.log('用户点击取消');
          }
        },
      });
  }

   // 点击销量排序、距离
   const tabClick = (tabItem:TabItem) => {
    const { id } = tabItem
    if (sortType === id) return

    setSortType(id)
   }

   // 获取商品列表
   const getShops = useCallback(async () => {
    if (!schoolId) return
    // 显示骨架屏的时候不显示loading
    // if(!showSkeletonRef.current) Taro.showLoading({ title: "加载中...", mask: true });
    Taro.showLoading({ title: "加载中...", mask: true });
     const params = {
      sortType,
      offset,
      cateId,
      schoolId,
      // ...locationInfo,
      ...requestParams.current
     }
     try {
       const res = await getShopList(params)
       const { data:{ shops = [], last = false} = {}} = res

       setIsloadFinish(last)

       const actionType = offset === 0 ? 'init' : 'concat'
       shopListDispatch({ type: actionType, payload: shops })
     } catch (error) {

     } finally{
      Taro.hideLoading();
      showSkeletonRef.current = false

      setShowSkeleton(false)

      Taro.stopPullDownRefresh();
     }

   },[cateId, offset, schoolId, sortType])

   const locationHandle = () => {
    Taro.navigateTo({
      url: '/pages/schoolList/index'
    })
   }


   // 点击分类某一项
   const categoryItemHandle = (cateItem) => {
     setCateId(cateItem.cateId)
   }

   // 点击进入商品详情页
   const shopItemClick = (item) => {
     Taro.navigateTo({
      url: `/pages/detail/index?shopId=${item.shopSId}`,
      complete: () => cachData(item)
    })
   }

   // 我的足迹缓存数据
   const cachData = async (curItem) => {
     const footmark = await getStoregeByKey('footmark') || []

     if (Array.isArray(footmark)) {
       const hasItem = footmark.findIndex(mark => mark.shopSId === curItem.shopSId)
       if (hasItem === -1) footmark.unshift(curItem)
     }
     Taro.setStorageSync('footmark', footmark.slice(0, 20))
   }

   // 轮播图跳转
   const swiperItemClick = ({jumpUrl}) => {
     if (jumpUrl.indexOf('luckCard') > -1) {
        Taro.navigateTo({ url: `/pages/luckCard/index`})
     } else {
       Taro.navigateTo({ url: `/pages/recruitInfo/index?url=${jumpUrl}`})
     }
   }
   /** banner下的tab end*/
  const getDataByCurrentTab: Function = (curTab: Number, tab: Tab) => {
    setTabIndex(curTab);
    setTabInfo(tab);
  };

   useEffect(() => {
    getSwiperList()
   }, []);

   useEffect(() => {
    getShops()
   },[getShops])

   useDidShow(() => {
    pageInit()
  })

  useShareAppMessage(res => {
    return {
      title: '校园颂',
      // imageUrl: '',
      path: '/pages/index/index'
    }
  })

  // 下拉刷新
  usePullDownRefresh(() => {
    showSkeletonRef.current = true
    if (offset !== 0)  setOffset(0);
    else getShops()
  });

   useReachBottom(() => {
    !isLoadFinish && setOffset(offset + 1)
   })

   /**
    * @description 自定义导航栏，传入的子元素
    */
   const renderCenter = <View className={styles.location} onClick={locationHandle}>
     <Image src={LocationIcon} className={styles.imgIcon} />
     <View className={styles.selectSchool}>
        <Text className={`${styles.txt} ${!schoolId ? styles.noSchool : null}`}>{school}</Text>
        { schoolId ? <Text className={styles.changeBtn}>「切换」</Text> : null }
     </View>
     {/* {schoolId && <View className='at-icon at-icon-chevron-right'></View>} */}
   </View>

   const {navBarHeight, navBarExtendHeight, statusBarHeight} = Taro.globalSystemInfo

   const safeNavigateBar = [`padding-top:${navBarHeight + navBarExtendHeight + statusBarHeight}px`].join(';')

   return (
     <View className={styles.home}>
       {/* <View>{Taro.globalSystemInfo.navBarHeight}</View> */}
       {/* 自定义导航栏 */}
       <NavBar
         renderCenter={renderCenter}
         background='#ffa15a'
         color='#fff'
       />
       <View style={safeNavigateBar} className={styles.safeDistanse}></View>
       {/* swiper-banner */}
       <View className={styles.banner}>
        <Swiper
          className={styles.banner_swiper}
          indicatorColor='#aaa'
          indicatorActiveColor='#fff'
          circular
          indicatorDots
          autoplay
        >
            {
              swiperList.map((swiper, index) => {
                return (
                  <SwiperItem key={`swiper_${index}`} >
                    <View className={styles.swiper_item} onClick={() => swiperItemClick(swiper)}>
                      <Image className={styles.swiper_img} src={swiper.imageUrl} />
                    </View>
                  </SwiperItem>
                )
              })
            }
        </Swiper>
       </View>
       {/* TODO: */}
        {/* <Nav getDataByCurrentTab={getDataByCurrentTab} tabIndex={tabIndex}></Nav> */}
        {/* 种类+骨架屏 */}
        <Skeleton avatar row={3} loading={categoryLoading}>
          <Category list={categoryList} clickItem={categoryItemHandle}></Category>
        </Skeleton>
       {/* 销量、距离排列 */}
       <View className={styles.tabs}>
         {
           tabsBar.map((tab,index) => {
             return <View onClick={() => tabClick(tab)} className={`${styles.tab} ${sortType === tab.id ? styles.active : null}`} key={index}>{tab.name}</View>
           })
         }
       </View>
       {/* 商品列表+骨架屏 */}
        <View className={styles.shopList}>
          <Skeleton avatar title row={6} loading={!shopList.length} titleWidth='80%' >
            {
              shopList.map((shop, index) => {
                return <ProdItem
                  shop={shop}
                  key={`shop_${index}`}
                  clickHandle={() => { shopItemClick(shop) }}
                />
              })
            }
          </Skeleton>
          {shopList.length && isLoadFinish ? <NoMore /> : <View></View>}
        </View>
       {/* 暂无数据 */}
       {
         !showSkeleton && !shopList.length && (
          <van-empty description='暂无数据' image={NoDataIcon} />
         )
       }

       {/* 选择校区 */}
       {/* <AtFloatLayout isOpened title="选择校区">
        这是内容区 随你怎么写这是内容区 随你怎么写这是内容区 随你怎么写这是内容区
        随你怎么写这是内容区 随你怎么写这是内容区 随你怎么写
      </AtFloatLayout> */}
     </View>
   );
 }

 export default Home
